/**
 * Created by zhangxiaoyu on 16/12/14.
 */
angular.module("hyt.loginCtrl",[])

  .controller('loginCtrl', function($scope,$state,$ionicLoading,Storage,VerificationUser,Login,$cordovaDevice,$ionicPopup,$window,$http,ENV) {
    $scope.user={
      username:'',
      password:'',
      uuid:''
    };
    if (Storage.get('user')!=null){
      $scope.user=Storage.get('user');
    }
    $scope.changeNum=function(val) {
      $scope.user.password='';
      if (val.length == 11) {
        VerificationUser.getVerificationUser(JSON.stringify($scope.user));
        $scope.$on('VerificationUser.Updated', function() {
          var vftResult = VerificationUser.getResult();
          if (vftResult.success==true){
            if (vftResult.rows==1){
              $state.go('verification',{username:val});
            }
          }
        });
      }
    };

    $scope.loginClick=function(){
      //获取手机设备号
      document.addEventListener("deviceready", function () {
        $scope.user.uuid = $cordovaDevice.getUUID();
      }, false);
      //判断网络连接
      document.addEventListener("deviceready", onDeviceReady, false);
      function onDeviceReady() {
        checkConnection();
      }
      function checkConnection() {
        var networkState = navigator.connection.type;

        var states = {};
        states[Connection.UNKNOWN]  = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI]     = 'WiFi connection';
        states[Connection.CELL_2G]  = 'Cell 2G connection';
        states[Connection.CELL_3G]  = 'Cell 3G connection';
        states[Connection.CELL_4G]  = 'Cell 4G connection';
        states[Connection.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';

        if(states[networkState]=='No network connection'){
          $ionicLoading.show({
            noBackdrop: true,
            template: "请检查网络连接!",
            duration: 1500
          });
        }
      }
      $http.get(ENV.postUrl).then(function(success){

      },function(error){
        $ionicLoading.show({
          noBackdrop: true,
          template: "无网络连接!",
          duration: 1500
        });
      });
      if ($scope.user.username==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: '请输入账号',
          duration: 1500
        });
      }else if($scope.user.password==''){
        $ionicLoading.show({
          noBackdrop: true,
          template: '请输入密码',
          duration: 1500
        });
      }else {
        Login.getLogin(JSON.stringify($scope.user));
      }
    };
    $scope.$on('Login.Updated', function() {
      var result = Login.getResult();
      if (result.success==true){
        if (result.rows.baseDeptId!=null){
          Storage.set('loginResult',result);
          Storage.set('user',$scope.user);
          Storage.set('isLogin',1);
          $state.go('tab.workbench');
        }else {
          $ionicLoading.show({
            noBackdrop: true,
            template: '当前账号为货主端账号暂不支持公司端登录',
            duration: 1500
          });
        }
      }
      else {
        $ionicLoading.show({
          noBackdrop: true,
          template: result.msg,
          duration: 1500
        });
      }
    });
    $scope.callPhone = function (mobilePhone) {
      var confirmPopup = $ionicPopup.confirm({
        title:mobilePhone,
        okText:'呼叫',
        cancelText:'取消'
      });
      confirmPopup.then(function(res) {
        if (res) {
          $window.location.href = "tel:" + mobilePhone;
        }else {

        }
      });
    };
  })

  .controller('verificationCtrl', function($scope,$state,$ionicLoading,Storage,$stateParams,$interval,VerificationCode,Verification) {
    $scope.vftion={
      username:$stateParams.username,
      verificationcode:''
    };
    //设置验证码倒计时
    var timePromise=undefined;
    $scope.paracont = "获取验证码";
    $scope.timmer=function() {
      $scope.paraevent = true;
      var second=90;
      $("#verificationCode").attr("disabled", true);
      timePromise = $interval(function(){
        if(second<=0){
          $interval.cancel(timePromise);
          timePromise = undefined;
          second = 90;
          $("#verificationCode").attr("disabled", false);
          $scope.paracont = "重发验证码";
          $scope.paraevent = true;
        }else{
          $("#verificationCode").attr("disabled", true);
          $scope.paracont = second + "秒后可重发";
          second--;
        }
      },1000,100);
    };
    $scope.clearTimmer=function(){
      $interval.cancel(timePromise);
    };
    //获取验证码
    $scope.getVerificationcode=function(){
      $scope.timmer();
      VerificationCode.getVerificationCode(JSON.stringify($scope.vftion));
    };
    $scope.verification=function(){
      Verification.checkVerificationCode(JSON.stringify($scope.vftion));
      $scope.$on('Verification.Updated', function() {
        var result = Verification.getResult();
        if (result.success==true){
          if (result.msg=="验证通过"){
            $ionicLoading.show({
              noBackdrop: true,
              template: "验证通过",
              duration: 1500
            });
            $state.go('login');
          }
        }
      });
    };

    $("#verificate").attr("disabled", true);
    $scope.isNull=function(){
      if($scope.vftion.verificationcode!=''){
        $("#verificate").attr("disabled", false);
      }
      else {
        $("#verificate").attr("disabled", true);
      }
    }
  })
  .controller('forgetPwdCtrl', function($scope,$state,$ionicLoading,Storage,$interval,VerificationCode,Verification,ForgetPwd,CountExist) {
    $("#verificationCode").attr("disabled", true);
    $("#changePw").attr("disabled", true);
    $scope.forgetPwd={
      username:'',
      password:'',
      verificationcode:''
    };
    $scope.changeNum=function(val) {
      if (val.length == 11) {
        var countExist={
          username:val
        };
        CountExist.getCountExist(JSON.stringify(countExist));
      }else {
        $("#verificationCode").attr("disabled", true);
      }
    };
    $scope.$on('CountExist.Updated', function() {
      var result=CountExist.getResult();
      if (result.success==true){
        $("#verificationCode").attr("disabled", false);
      }else {
        $("#verificationCode").attr("disabled", true);
        $ionicLoading.show({
          noBackdrop: true,
          template: "账号不存在",
          duration: 1500
        });
      }
    });
    //设置验证码倒计时
    var timePromise=undefined;
    $scope.paracont = "获取验证码";
    $scope.timmer=function() {
      $scope.paraevent = true;
      var second=90;
      $("#verificationCode").attr("disabled", true);
      timePromise = $interval(function(){
        if(second<=0){
          $interval.cancel(timePromise);
          timePromise = undefined;
          second = 90;
          $("#verificationCode").attr("disabled", false);
          $scope.paracont = "重发验证码";
          $scope.paraevent = true;
        }else{
          $("#verificationCode").attr("disabled", true);
          $scope.paracont = second + "秒后可重发";
          second--;
        }
      },1000,100);
    };
    $scope.cleanTimmer=function(){
      $interval.cancel(timePromise);
    };
    //获取验证码
    $scope.getVerificationcode=function(){
      $scope.timmer();
      VerificationCode.getVerificationCode(JSON.stringify($scope.forgetPwd));
    };
    $scope.changePw=function(){
      Verification.checkVerificationCode(JSON.stringify($scope.forgetPwd));
      $scope.$on('Verification.Updated', function() {
        var result = Verification.getResult();
        if (result.success==true){
          if (result.msg=="验证通过"){
            ForgetPwd.getForgetPwd(JSON.stringify($scope.forgetPwd));
          }else {
            $ionicLoading.show({
              noBackdrop: true,
              template: "验证码错误",
              duration: 1500
            });
          }
        }else {
          $ionicLoading.show({
            noBackdrop: true,
            template: "验证码错误",
            duration: 1500
          });
        }
      });
    };
    $scope.$on('ForgetPwd.Updated', function() {
      var result=ForgetPwd.getResult();
      if (result.success==true){
        $ionicLoading.show({
          noBackdrop: true,
          template: result.msg,
          duration: 1500
        });
        $state.go('login');
        $scope.cleanTimmer();
      }
    });
    $scope.changePwNum=function(){
      if($scope.forgetPwd.password!=''){
        $("#changePw").attr("disabled", false);
      }
      else {
        $("#changePw").attr("disabled", true);
      }
    }
  })
